#!/bin/bash -x

case "$XT_MULTI" in
*xtables-nft-multi)
	;;
*)
	echo "skip $XT_MULTI"
	exit 0
	;;
esac

set -e

load_ruleset() {
	$XT_MULTI ebtables-restore <<EOF
*filter
-A FORWARD --mark 0x1 -c 1 2
-A FORWARD --mark 0x2 -c 2 3
EOF
}

load_ruleset

$XT_MULTI ebtables -L 0 && exit 1

EXPECT='--mark 0x1 -j CONTINUE , pcnt = 1 -- bcnt = 2'
diff -u -b <(echo -e "$EXPECT") <($XT_MULTI ebtables -L FORWARD 1 --Lc)

EXPECT='--mark 0x2 -j CONTINUE , pcnt = 2 -- bcnt = 3'
diff -u -b <(echo -e "$EXPECT") <($XT_MULTI ebtables -v -L FORWARD 2 --Lc)

[[ -z $($XT_MULTI ebtables -L FORWARD 3) ]]

$XT_MULTI ebtables -S FORWARD 0 && exit 1

EXPECT='[1:2] -A FORWARD --mark 0x1 -j CONTINUE'
diff -u <(echo -e "$EXPECT") <($XT_MULTI ebtables -v -S FORWARD 1)

EXPECT='[2:3] -A FORWARD --mark 0x2 -j CONTINUE'
diff -u <(echo -e "$EXPECT") <($XT_MULTI ebtables -v -S FORWARD 2)

[[ -z $($XT_MULTI ebtables -S FORWARD 3) ]]

$XT_MULTI ebtables -v -Z FORWARD 0 && exit 1

[[ -z $($XT_MULTI ebtables -v -Z FORWARD 1) ]]
EXPECT='[0:0] -A FORWARD --mark 0x1 -j CONTINUE
[2:3] -A FORWARD --mark 0x2 -j CONTINUE'
diff -u <(echo -e "$EXPECT") <($XT_MULTI ebtables -v -S | grep -v '^-P')

[[ -z $($XT_MULTI ebtables -v -Z FORWARD 2) ]]
EXPECT='[0:0] -A FORWARD --mark 0x1 -j CONTINUE
[0:0] -A FORWARD --mark 0x2 -j CONTINUE'
diff -u <(echo -e "$EXPECT") <($XT_MULTI ebtables -v -S | grep -v '^-P')

$XT_MULTI ebtables -v -Z FORWARD 3 && exit 1

load_ruleset

[[ -z $($XT_MULTI ebtables -v -L -Z FORWARD 1) ]]
EXPECT='[0:0] -A FORWARD --mark 0x1 -j CONTINUE
[2:3] -A FORWARD --mark 0x2 -j CONTINUE'
diff -u <(echo -e "$EXPECT") <($XT_MULTI ebtables -v -S | grep -v '^-P')

[[ -z $($XT_MULTI ebtables -v -L -Z FORWARD 2) ]]
EXPECT='[0:0] -A FORWARD --mark 0x1 -j CONTINUE
[0:0] -A FORWARD --mark 0x2 -j CONTINUE'
diff -u <(echo -e "$EXPECT") <($XT_MULTI ebtables -v -S | grep -v '^-P')

load_ruleset

$XT_MULTI ebtables -v -Z -L FORWARD 0 && exit 1

EXPECT='--mark 0x1 -j CONTINUE
Zeroing chain `FORWARD'\'
diff -u -b <(echo -e "$EXPECT") <($XT_MULTI ebtables -v -Z -L FORWARD 1)
EXPECT='[0:0] -A FORWARD --mark 0x1 -j CONTINUE
[0:0] -A FORWARD --mark 0x2 -j CONTINUE'
diff -u <(echo -e "$EXPECT") <($XT_MULTI ebtables -v -S | grep -v '^-P')

EXPECT='--mark 0x2 -j CONTINUE
Zeroing chain `FORWARD'\'
diff -u -b <(echo -e "$EXPECT") <($XT_MULTI ebtables -v -Z -L FORWARD 2)

$XT_MULTI ebtables -v -Z -L FORWARD 0 && exit 1

EXPECT='Zeroing chain `FORWARD'\'
diff -u -b <(echo -e "$EXPECT") <($XT_MULTI ebtables -v -Z -L FORWARD 3)

load_ruleset

[[ -z $($XT_MULTI ebtables -v -D FORWARD 1) ]]
EXPECT='[2:3] -A FORWARD --mark 0x2 -j CONTINUE'
diff -u <(echo -e "$EXPECT") <($XT_MULTI ebtables -v -S | grep -v '^-P')

load_ruleset

[[ -z $($XT_MULTI ebtables -v -D FORWARD 2) ]]
EXPECT='[1:2] -A FORWARD --mark 0x1 -j CONTINUE'
diff -u <(echo -e "$EXPECT") <($XT_MULTI ebtables -v -S | grep -v '^-P')

$XT_MULTI ebtables -v -D FORWARD 3 && exit 1

exit 0
